<?php

namespace App\Http\Controllers\QH_Api;

use App\Http\Controllers\TK_Api\ApiBaseController;
use App\Models\BaseModel;
use App\Models\Qh_Article;
use App\Models\Qh_Banner;
use App\Models\Qh_MiniProgramComponent;
use App\Models\Qh_Notice;
use App\Models\Qh_School;
use App\Models\Qh_SchoolArticle;
use App\Models\Qh_SchoolSpec;
use App\Models\TQ_Config;
use Auth;
use DB;
use Exception;
use Illuminate\Http\JsonResponse;
use LaravelIdea\Helper\App\Models\_IH_BaseModel_C;
use LaravelIdea\Helper\App\Models\_IH_Qh_SchoolSpec_C;

class SchoolController extends ApiBaseController
{
    /**
     * 招生院校首页
     * @return JsonResponse|object
     */
    public function index() {
        // banner、通知、热门学校、招生资讯
        $config = TQ_Config::where('key', 'school_config')->first();
        if (!$config) {
            TQ_Config::create([
                'banner' => [],
                'notice' => null
            ]);
        }
        $valueJson = json_decode($config->value);
        $data['banner'] = Qh_Banner::whereIn('id', $valueJson->banner)->get();
        if($valueJson->notice) {
            $component = Qh_MiniProgramComponent::find($valueJson->notice);
            $data['notice'] = json_decode($component->data);
        }else {
            $data['notice'] = null;
        }
        //$data['school'] = Qh_School::whereIn('id', $valueJson->school)->get();
        //$data['news'] = Qh_SchoolArticle::whereIn('id', $valueJson->school)->get();

        $data['school'] = Qh_School::filter(request()->all())->orderByDesc('readCount')->limit(3)->get();
        $data['news'] = Qh_SchoolArticle::filter(request()->all())->where('type', 2)->orderByDesc('readCount')->limit(3)->get();

        return $this->restful($data);
    }

    /**
     * 学校列表（找院校）
     * @return JsonResponse|object
     */
    public function schoolList() {
        $list = Qh_School::filter(request()->all())
            ->selectRaw('id, name, tags, logo, city, level, province, type, bxType')
            // ->inRandomOrder()
            ->get();
        return $this->restful([
            'list' => $list,
            'count' => $list->count()
        ]);
    }

    /**
     * 学校详情页
     * @param int $id
     * @return JsonResponse|object
     */
    public function school(int $id) {
        $school = Qh_School::findOrFail($id);
        $school->readCount += 1;
        $school->save();

        return $this->restful($school);
    }

    /**
     * 获取学校下的专业
     * @param int $id
     * @return JsonResponse|object
     */
    public function getSchoolSpecBySchool(int $id) {
        $school = Qh_School::findOrFail($id);
        $spec = $school->spec()
            ->where('level', 3)
            ->select('*')
            ->with(['parent' => function($q) {
                $q->select(['id', 'parentId', 'name'])->with(['parent' => function($q) {
                    $q->select(['id', 'name']);
                }]);
            }])
            ->get();

        return $this->restful($spec);
    }

    /**
     * 获取学校下的招生计划
     * @param int $id
     * @return JsonResponse|object
     */
    public function getSchoolPlan(int $id) {
        $wh = [];
        if (!empty(request('year'))) $wh[] = ['qh_school_plan.year', '=', request('year')];
        if (!empty(request('whcd'))) $wh[] = ['qh_school_plan.whcd', '=', request('whcd')];
        if (!empty(request('class'))) $wh[] = ['qh_school_plan.class', '=', request('class')];
        if (!empty(request('c1'))) $wh[] = ['qh_school_plan.c1', '=', request('c1')];

        $list = DB::table('qh_school_plan')->where('schoolId', $id)
            ->selectRaw('qh_school_specs.*, qh_school_plan.class, qh_school_plan.year, qh_school_plan.num, qh_school_plan.whcd, qh_school_plan.xz, qh_school_plan.price, qh_school_plan.c1, qh_school_plan.remarks')
            ->join('qh_school_specs', 'qh_school_plan.schoolSpecId', '=', 'qh_school_specs.id')
            ->where($wh)
            ->get();


        return $this->restful($list);
    }


    /**
     * 获取招生简章列表
     * @return JsonResponse|object
     */
    public function getNews() {
        $article = Qh_SchoolArticle::filter(request()->all())->where('type', 1)->get();
        return $this->restful($article);
    }

    /**
     * 获取招生资讯
     * @return JsonResponse|object
     */
    public function getInfo() {
        $article = Qh_SchoolArticle::filter(request()->all())->where('type', 2)->get();
        return $this->restful($article);
    }


    /**
     * 获取文章详情
     * @param int $id
     * @return JsonResponse|object
     */
    public function article(int $id) {
        $article = Qh_SchoolArticle::findOrFail($id);

        return $this->restful($article);
    }

    /**
     * 专业列表
     * @return JsonResponse|object
     */
    public function getSchoolSpecList() {
        $input = request()->all();
        $input['level'] = 3;
        $list = Qh_SchoolSpec::filter($input)
            ->select('*')
            ->with(['parent' => function($q) {
                $q->select(['id', 'parentId', 'name'])->with(['parent' => function($q) {
                    $q->select(['id', 'name']);
                }]);
            }])
            ->get();
        return $this->restful($list);
    }

    public function getSchoolSpecList2() {
        $input = request()->all();
        $input['level'] = 3;
        $list = Qh_SchoolSpec::filter($input)
            ->select('*')
            ->with(['parent' => function($q) {
                $q->select(['id', 'parentId', 'name'])->with(['parent' => function($q) {
                    $q->select(['id', 'name']);
                }]);
            }])
            ->paginate(request('perPage', 15));
        return $this->restful($list);
    }

    /**
     * 关注/取消关注
     * @return JsonResponse|object
     * @throws Exception
     */
    public function follow() {
        $id = request('id');
        if (empty($id)) {
            throw new Exception('学校不存在');
        }

        if (Auth::guard('api')->check()) {
            $this->user->followedSchool()->toggle([$id]);
        }
        return $this->restful();
    }

    /**
     * 根据id获取专业
     * @param $id
     * @return JsonResponse|object
     */
    public function getSpecById($id) {
        $spec = Qh_SchoolSpec::where('id', $id)
            ->with(['parent' => function($q) {
                $q->select(['id', 'parentId', 'name'])->with(['parent' => function($q) {
                    $q->select(['id', 'name']);
                }]);
            }])
            ->first();

        return $this->restful($spec);
    }
}
